﻿using EWSEditor.Forms;
using Microsoft.Exchange.WebServices.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EWSEditor.CRM.Forms
{
    public partial class EmailValidatorFilterForm : Form
    {

        private ExchangeService _exchangeService;
        public EmailValidatorFilterForm(ExchangeService service)
        {
            InitializeComponent();
            _exchangeService = service;
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                bool validInput = ValidateInput();

                if (!validInput)
                {
                    MessageBox.Show("Please provide a value for each selected filter parameter.");
                    return;
                }

                SearchFilter filter = GetSearchFilter();
                ItemView view = new ItemView(50);
                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
                view.PropertySet = PropertySet.FirstClassProperties;
                
                FindItemsResults<Item> results = _exchangeService.FindItems(WellKnownFolderName.Inbox, filter, view);

                if (results.Items.Count < 1)
                {
                    MessageBox.Show("No items found matching the specified criteria.");
                    return;
                }

                OpenGrid(results);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
            }
        }

        private bool ValidateInput()
        {
            if (chkSender.Checked)
            {
                if ((string.IsNullOrEmpty(txtSenderEmail.Text) || (!txtSenderEmail.Text.Contains("@"))))
                {
                    return false;
                }
            }

            if (chkSubject.Checked)
            {
                if (string.IsNullOrEmpty(txtSubject.Text))
                {
                    return false;
                }
            }

            return true;
        }

        private void OpenGrid(FindItemsResults<Item> results)
        {
            List<ItemId> itemIdList = new List<ItemId>();

            foreach(Item item in results.Items)
            {
                itemIdList.Add(item.Id);
            }

            ItemsContentForm.ShowFilteredItems(ItemFilterMode.EmailValidator, "Email Validator", itemIdList, _exchangeService);
            this.Close();
        }

        private SearchFilter GetSearchFilter()
        {
            List<SearchFilter> searchfiltercollection = new List<SearchFilter>();

            if (chkSender.Checked)
            {
                searchfiltercollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.From, txtSenderEmail.Text));
            }
            if (chkReceivedAfter.Checked)
            {
                searchfiltercollection.Add(new SearchFilter.IsGreaterThan(EmailMessageSchema.DateTimeReceived, dtEmailReceivedAfter.Value));
            }
            if (chkSubject.Checked)
            {
                searchfiltercollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, txtSubject.Text));
            }

            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(Microsoft.Exchange.WebServices.Data.LogicalOperator.And, searchfiltercollection.ToArray());
            return searchFilter;
        }

        private void picInfo_MouseHover(object sender, EventArgs e)
        {
            ToolTip tip = new ToolTip();
            tip.SetToolTip(this.picInfo, Strings.EMAILVALIDATORINFO);
        }

        private void chkSubject_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSubject.Checked)
            {
                txtSubject.Enabled = true;
                btnGo.Enabled = true;
            }
            else
            {
                txtSubject.Enabled = false;
            }

            CheckForInvalidFilter();

        }

        private void CheckForInvalidFilter()
        {
            if ((!chkSubject.Checked) && (!chkSender.Checked) && (!chkReceivedAfter.Checked))
            {
                btnGo.Enabled = false;
            }
        }

        private void chkSender_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSender.Checked)
            {
                txtSenderEmail.Enabled = true;
                btnGo.Enabled = true;
            }
            else
            {
                txtSenderEmail.Enabled = false;
            }
            CheckForInvalidFilter();

        }

        private void chkReceivedAfter_CheckedChanged(object sender, EventArgs e)
        {
            if (chkReceivedAfter.Checked)
            {
                dtEmailReceivedAfter.Enabled = true;
                btnGo.Enabled = true;
            }
            else
            {
                dtEmailReceivedAfter.Enabled = false;
            }
            CheckForInvalidFilter();
        }
    }
}
